
package com.lzx.iteam.net;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.lzx.iteam.R;
import com.lzx.iteam.bean.CloudGroup;
import com.lzx.iteam.provider.CloudDBOperation;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class CloudGroupListCenter {


    private static final String TAG = "GetGroupsListMessage";

    private ArrayList<CloudGroup> mLocalGroupList = new ArrayList<CloudGroup>();
    private CloudGroupDataListener mListener;
    private CloudDBOperation mCloudDBOperation;

    public interface CloudGroupDataListener {
        void onChange(ArrayList<CloudGroup> groupList);

        void onNoChange(ArrayList<CloudGroup> groupList);

        void onError(int errNum, String obj);
    }

    private static final int MSG_GROUP_GETLIST = 1000;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_GROUP_GETLIST:
                    if (msg.arg1 == 0) {
                        @SuppressWarnings("unchecked")
                        ArrayList<CloudGroup> cloudGroupList = (ArrayList<CloudGroup>) msg.obj;
                        /*ArrayList<CloudGroup> localGroupList = new ArrayList<CloudGroup>();
                        localGroupList.addAll(mLocalGroupList);
                        *//**
                         * 如果匹配完毕后需要更新，则先清除mLocalGroupList变量，之后重新查询后刷新界面
                         *//*
                        if (updateCloudGroupData(localGroupList, cloudGroupList)) {
                            mLocalGroupList.clear();
                            notifyCloudGroupUpdate();
                        } else {
                            if (mListener != null) mListener.onNoChange(mLocalGroupList);
                        }*/
                        if (mListener != null) mListener.onChange(cloudGroupList);

                    } /*else if (msg.arg1 == 1002 || msg.arg1 == 1003 || msg.arg1 == 1005){
                        if (mListener != null) mListener.onError(msg.arg1, (String) msg.obj);
                    } */else {
                        if (mListener != null) mListener.onError(msg.arg1, (String) msg.obj);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private static CloudGroupListCenter sInstance;
    private Context mContext;

    private CloudGroupListCenter(Context context) {
        mContext = context;
        mLocalLogin = LocalLogin.getInstance();
        mCloudDBOperation = new CloudDBOperation(context);
    }

    public static CloudGroupListCenter getInstance(Context c) {
        if (sInstance == null) {
            sInstance = new CloudGroupListCenter(c);
        }
        return sInstance;
    }

/*
    private ArrayList<CloudGroup> getLocalGroupList() {
        ArrayList<CloudGroup> groupList = new ArrayList<CloudGroup>();
        Cursor cursor = null;
        try {
            cursor = mContext.getContentResolver().query(CloudGroupDbo.CONTENT_URI,
                    null, null, null, CloudGroupDbo.GROUP_TYPE);
            if (cursor == null) return groupList;
            while (cursor.moveToNext()) {
                CloudGroup groupItem = new CloudGroup();
                groupItem.groupId = cursor.getLong(cursor.getColumnIndex(CloudContactsDB.CloudGroupDbo.GROUP_ID));
                groupItem.groupName = cursor.getString(cursor.getColumnIndex(CloudContactsDB.CloudGroupDbo.GROUP_NAME));
                groupItem.groupType = cursor.getInt(cursor.getColumnIndex(CloudContactsDB.CloudGroupDbo.GROUP_TYPE));
                groupItem.contactId = cursor.getString(cursor.getColumnIndex(CloudContactsDB.CloudGroupDbo.CONTACT_ID));
                groupItem.contactCount = cursor.getInt(cursor.getColumnIndex(CloudContactsDB.CloudGroupDbo.CONTACT_COUNT));
                groupItem.memberCount = cursor.getInt(cursor.getColumnIndex(CloudContactsDB.CloudGroupDbo.MEMBER_COUNT));
                groupItem.updateTime = cursor.getLong(cursor.getColumnIndex(CloudContactsDB.CloudGroupDbo.UPDATE_TIME));
                groupItem.groupImg = cursor.getString(cursor.getColumnIndex(CloudContactsDB.CloudGroupDbo.GROUP_IMG));
                groupItem.userType = cursor.getString(cursor.getColumnIndex(CloudContactsDB.CloudGroupDbo.USER_TYPE));
                groupItem.isNew = cursor.getString(cursor.getColumnIndex(CloudContactsDB.CloudGroupDbo.IS_NEW));
                groupItem.hasTags = cursor.getString(cursor.getColumnIndex(CloudContactsDB.CloudGroupDbo.HAS_TAGS));

                groupList.add(groupItem);
            }
        } finally {
            if (cursor != null) cursor.close();
        }
        return groupList;
    }
*/

    /**
     * 此方法会对比本地查询的结果和从服务器获取的结果
     * 如果本地不存在，则将获取的结果存入数据库
     * 如果本地已经存在的数据中包含从服务器段获取的，则更新数据库(并删除本地的这个数据)
     * 本地和获取的匹配完毕之后，若本地的变量还有数据，则将剩下的数据从数据库中全部删除
     *
     * @param localGroupList
     * @param cloudGroupList
     * @return
     */
    private boolean updateCloudGroupData(ArrayList<CloudGroup> localGroupList, ArrayList<CloudGroup> cloudGroupList) {
        boolean needUpdate = false;
        //如果本地没有，则将从服务器获取的插入数据库，成功则返回true
        if (localGroupList.size() == 0) {
            for (int i = 0; i < cloudGroupList.size(); i++) {
                needUpdate |= (mCloudDBOperation.insertCloudGroup(cloudGroupList.get(i)) != 0);
            }
            return needUpdate;
        }
        //如果本地有
        Iterator<CloudGroup> i = cloudGroupList.iterator();
        while (i.hasNext()) {
            CloudGroup cloudItem = i.next();
            i.remove();
            //如果本地的里面包含从服务器获取的，则将本地里面的删除掉
            CloudGroup localItem = removeGroupById(cloudItem.groupId, localGroupList);
            //如果不包含，则添加进数据库
            if (localItem == null) {
                needUpdate |= (mCloudDBOperation.insertCloudGroup(cloudItem) != 0);
                continue;
            }
            //如果包含，且更新时间新于本地的，则更新数据库里的
//            if (cloudItem.updateTime > localItem.updateTime) {
//            if(cloudItem.updateTime!=localItem.updateTime){
            needUpdate |= (mCloudDBOperation.updateCloudGroupItem(cloudItem) > 0);
            continue;
//            }
        }
        //如果服务器获取到的匹配完毕，本地还有的话，则删除数据库中的本地剩下的过时数据
        if (localGroupList.size() > 0) {
            needUpdate |= (deleteCloudGroupItem(localGroupList) > 0);
        }

        return needUpdate;
    }

    private int deleteCloudGroupItem(ArrayList<CloudGroup> groupList) {
        if (groupList == null || groupList.size() == 0) {
            Log.w(TAG, "deleteCloudGroupItem with null group list.");
            return 0;
        }

       /* StringBuilder sb = new StringBuilder();
        sb.append(CloudGroupDbo.GROUP_ID + " IN (")
                .append(groupList.get(0).groupId);
        for (int i = 1; i < groupList.size(); i++) {
            sb.append(',').append(groupList.get(i).groupId);
        }
        sb.append(')');
        return mContext.getContentResolver().delete(CloudGroupDbo.CONTENT_URI, sb.toString(), null);
*/
        for (int i = 0; i < groupList.size(); i++) {
            mCloudDBOperation.deleteGroupByGroupId(groupList.get(i).groupId + "");
        }
        return 1;
    }

/*
    public int deleteCloudGroupItem(long gid) {
        if (gid == 0) {
            Log.w(TAG, "delete cloud group item with 0.");
            return 0;
        }

        int ret = mContext.getContentResolver().delete(
                CloudGroupDbo.CONTENT_URI, CloudGroupDbo.GROUP_ID + "=" + gid, null);
        if (ret > 0) notifyCloudGroupUpdate();

        return ret;
    }
*/

    public void eraseGroupData() {
        /*mContext.getContentResolver().delete(CloudGroupDbo.CONTENT_URI, null, null);*/
        mCloudDBOperation.deleteAllGroup();
//        notifyCloudGroupUpdate();
    }

    /*private void notifyCloudGroupUpdate() {
        mLocalGroupList = mCloudDBOperation.getLocalGroupList();
        if (mListener != null) mListener.onChange(mLocalGroupList);
    }*/

/*
    private Uri insertCloudGroupItem(CloudGroup item) {
        ContentValues values = new ContentValues();
        values.put(CloudGroupDbo.GROUP_ID, item.groupId);
        values.put(CloudGroupDbo.GROUP_NAME, item.groupName);
        values.put(CloudGroupDbo.GROUP_TYPE, item.groupType);
        values.put(CloudGroupDbo.CONTACT_ID, item.contactId);
        values.put(CloudGroupDbo.CONTACT_COUNT, item.contactCount);
        values.put(CloudGroupDbo.MEMBER_COUNT, item.memberCount);
        values.put(CloudGroupDbo.UPDATE_TIME, item.updateTime);
        values.put(CloudGroupDbo.GROUP_IMG, item.groupImg);
        values.put(CloudGroupDbo.USER_TYPE, item.userType);
        values.put(CloudGroupDbo.IS_NEW, item.isNew);
        values.put(CloudGroupDbo.HAS_TAGS, item.hasTags);
        return mContext.getContentResolver().insert(CloudGroupDbo.CONTENT_URI, values);
    }
*/

/*
    private int updateCloudGroupItem(CloudGroup item) {
        ContentValues values = new ContentValues();
        values.put(CloudGroupDbo.GROUP_NAME, item.groupName);
        values.put(CloudGroupDbo.GROUP_TYPE, item.groupType);
        values.put(CloudGroupDbo.CONTACT_ID, item.contactId);
        values.put(CloudGroupDbo.CONTACT_COUNT, item.contactCount);
        values.put(CloudGroupDbo.MEMBER_COUNT, item.memberCount);
        values.put(CloudGroupDbo.UPDATE_TIME, item.updateTime);
        values.put(CloudGroupDbo.GROUP_IMG, item.groupImg);
        values.put(CloudGroupDbo.USER_TYPE, item.userType);
        values.put(CloudGroupDbo.IS_NEW, item.isNew);
        values.put(CloudGroupDbo.HAS_TAGS, item.hasTags);
//        values.put(CloudGroupDbo.CREATOR_UID, item.creator_uid);
        return mContext.getContentResolver().update(CloudGroupDbo.CONTENT_URI,
                values, CloudGroupDbo.GROUP_ID + "=" + item.groupId, null);
    }
*/

    private CloudGroup removeGroupById(long gid, ArrayList<CloudGroup> cloudGroupList) {
        for (int i = 0; i < cloudGroupList.size(); i++) {
            if (cloudGroupList.get(i).groupId == gid) {
                return cloudGroupList.remove(i);
            }
        }
        return null;
    }

    public void reqCloudGroupList(Context c, Message callback) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        // nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGE_SIZE, Integer.toString(10)));
        // nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGE_INDEX, Integer.toString(0)));
        GetGroupListMsg getGroup = new GetGroupListMsg(c, callback);
        getGroup.mApi = AsynHttpClient.API_GROUP_GETLIST;
        getGroup.mParams = nvps;
        AsynHttpClient.getInstance(c).execCcHttp(getGroup);
    }

    public void setGroupListListener(CloudGroupDataListener listener) {
        mListener = listener;
    }

    public void removeGroupListListener() {
        mListener = null;
    }

    private LocalLogin mLocalLogin;

    public ArrayList<CloudGroup> getCloudGroupList(Context context,String uid) {
        mLocalGroupList.clear();
        mLocalGroupList = mCloudDBOperation.getLocalGroupList(uid);
        reqCloudGroupList(context, mHandler.obtainMessage(MSG_GROUP_GETLIST));
        return mLocalGroupList;
    }

    /**************************************************/

    public static boolean isT9Key(String key) {
        if (TextUtils.isEmpty(key)) return true;

        char[] c = key.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] <= '9' && c[i] >= '0') {
                return true;
            }
        }

        return false;
    }

    public static String searchReplace(String key) {
        if (TextUtils.isEmpty(key)) return "";

        if (key.contains("*") && key.charAt(0) != '*') {
            key = "*" + key;
        }

        return key;
    }

    public static void startActivitySafe(Context context, Intent intent) {
        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(context,
                    context.getString(R.string.activity_not_found),
                    Toast.LENGTH_LONG).show();
        }
    }
}
